<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select
        v-model="listQuery.authorId"
        filterable
        placeholder="请选择用户"
        clearable
        style="width: 120px;"
      >
        <el-option
          v-for="item in listGenAhthorCombo"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button
        v-if="isP('GenTableAdd')"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-plus"
        @click="openDialogTableForm(false)"
      >新增
      </el-button>
      <el-button-group>
        <el-button
          v-if="isP('GenCreate')"
          type="success"
          @click="createCode(1)"
        >Model
        </el-button>
        <el-button
          v-if="isP('GenCreate')"
          type="success"
          @click="createCode(2)"
        >VO
        </el-button>
        <el-button
          v-if="isP('GenCreate')"
          type="success"
          @click="createCode(3)"
        >DTO
        </el-button>
        <el-button
          v-if="isP('GenCreate')"
          type="success"
          @click="createCode(4)"
        >Dao
        </el-button>
        <el-button
          v-if="isP('GenCreate')"
          type="success"
          @click="createCode(5)"
        >Service
        </el-button>
        <el-button
          v-if="isP('GenCreate')"
          type="success"
          @click="createCode(6)"
        >Controller
        </el-button>
        <el-button
          v-if="isP('GenCreate')"
          type="primary"
          @click="createAllCode(0)"
        >全部生成
        </el-button>
        <el-button
          v-if="isP('GenCreateSql')"
          type="primary"
          @click="createSqlCode()"
        >Sql脚本
        </el-button>
      </el-button-group>
      <el-button
        v-if="isP('GenLoadField')"
        type="success"
        @click="loadDbField()"
      >加载数据表字段
      </el-button>
      <br>
      <el-button-group style="margin-top: 10px;">
        <el-button
          v-if="isP('GenCreate')"
          type="success"
          @click="createCode(11)"
        >Api
        </el-button>
        <el-button
          v-if="isP('GenCreate')"
          type="success"
          @click="createCode(12)"
        >Index
        </el-button>
        <el-button
          v-if="isP('GenCreate')"
          type="success"
          @click="createCode(13)"
        >Components
        </el-button>
        <el-button
          v-if="isP('GenCreate')"
          type="success"
          @click="createCode(14)"
        >Router
        </el-button>
      </el-button-group>
    </div>
    <el-table
      ref="genTable"
      v-loading="listLoading"
      :data="list"
      border
      fit
      style="width: 100%;"
      @current-change="handleCurrentChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column
        type="index"
        width="50"
      />
      <el-table-column
        prop="tablename"
        label="数据表名"
        width="120"
      />
      <el-table-column
        prop="description"
        label="名称"
        width="100"
      />
      <el-table-column
        prop="javaPackage"
        label="Java包名"
        width="120"
      />
      <el-table-column
        prop="isPage"
        label="是否分页"
        width="100"
        :formatter="isPageFormatter"
      />
      <el-table-column
        prop="isAdd"
        label="是否新增"
        width="100"
        :formatter="isAddFormatter"
      />
      <el-table-column
        prop="isUpdate"
        label="是否修改"
        width="100"
        :formatter="isUpdateFormatter"
      />
      <el-table-column
        prop="isDelete"
        label="是否删除"
        width="100"
        :formatter="isDeleteFormatter"
      />
      <el-table-column
        prop="isView"
        label="是否查看"
        width="100"
        :formatter="isViewFormatter"
      />

      <el-table-column align="center" label="操作" min-width="160">
        <template slot-scope="scope">
          <el-button
            v-if="isP('GenTableUpdate')"
            style="margin-left: 10px"
            type="primary"
            size="mini"
            @click="openDialogTableForm(true,scope.row)"
          >修改
          </el-button>
          <el-button
            v-if="isP('GenTableDelete')"
            style="margin-left: 10px"
            type="danger"
            size="mini"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
          <el-button
            style="margin-left: 10px"
            type="primary"
            size="mini"
            @click="handleViewField(scope.row)"
          >字段明细
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 弹出框新增table -->
    <el-dialog title="数据表信息" :visible.sync="dialogTableFormVisible">
      <el-form
        ref="tableForm"
        :model="tableForm"
        :rules="rules"
        label-position="right"
        label-width="120px"
        style="width: 600px; margin-left:20px; margin-right: 0px;"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="数据表名" prop="tablename">
              <el-input v-model="tableForm.tablename" maxlength="60" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="描述" prop="description">
              <el-input v-model="tableForm.description" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="Java包名" prop="javaPackage">
              <el-input v-model="tableForm.javaPackage" maxlength="60" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="apiUrl全局配置" prop="apiUrl">
              <el-input v-model="tableForm.apiUrl" maxlength="20" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否分页" prop="isPage">
              <el-select v-model="tableForm.isPage" placeholder="请选择" style="width: 100%;">
                <el-option
                  v-for="item in yesNoOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否新增" prop="isAdd">
              <el-select v-model="tableForm.isAdd" placeholder="请选择" style="width: 100%;">
                <el-option
                  v-for="item in yesNoOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否修改" prop="isUpdate">
              <el-select v-model="tableForm.isUpdate" placeholder="请选择" style="width: 100%;">
                <el-option
                  v-for="item in yesNoOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否删除" prop="isDelete">
              <el-select v-model="tableForm.isDelete" placeholder="请选择" style="width: 100%;">
                <el-option
                  v-for="item in yesNoOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否查看" prop="isView">
              <el-select v-model="tableForm.isView" placeholder="请选择" style="width: 100%;">
                <el-option
                  v-for="item in yesNoOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="一级模块代码" prop="firstCode">
              <el-input v-model="tableForm.firstCode" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="一级模块名称" prop="firstName">
              <el-input v-model="tableForm.firstName" maxlength="20" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="二级模块代码" prop="secondCode">
              <el-input v-model="tableForm.secondCode" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="二级模块名称" prop="secondName">
              <el-input v-model="tableForm.secondName" maxlength="20" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="主键生成方式" prop="pkCreate">
              <el-select v-model="tableForm.pkCreate" placeholder="请选择" style="width: 100%;">
                <el-option
                  v-for="item in pkCreateOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="主键字段" prop="pkField">
              <el-input v-model="tableForm.pkField" maxlength="40" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="排序字段" prop="orderField">
              <el-input v-model="tableForm.orderField" maxlength="40" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button @click="dialogTableFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveTable">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="代码生成" :visible.sync="dialogGenCodeVisible" width="900px">
      <el-form
        ref="genCodeForm"
        label-position="right"
        label-width="100px"
        style="width: 800px; margin-left:20px; margin-right: 20px;"
      >
        <el-input
          v-model="genCodeText"
          type="textarea"
          :rows="20"
        />
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button @click="dialogGenCodeVisible = false">取 消</el-button>
        <el-button type="primary" @click="copyCode">拷贝</el-button>
        <el-button type="success" @click="checkFileExist">创建</el-button>
      </div>
    </el-dialog>
    <el-dialog title="Sql脚本" :visible.sync="dialogGenSqlCodeVisible" width="900px">
      <el-form
        ref="genCodeForm"
        label-position="right"
        label-width="100px"
        style="width: 800px; margin-left:20px; margin-right: 20px;"
      >
        <el-input
          v-model="genSqlCodeText"
          type="textarea"
          style="font-size: 16px;"
          :rows="20"
        />
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button @click="dialogGenSqlCodeVisible = false">取 消</el-button>
        <el-button type="primary" @click="copySqlCode">拷贝</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listGenTable, deleteGenTable, addGenTable, updateGenTable } from '@/api/gen/table'
import { getGenCode, checkFileExist, createFile, getGenSqlCode } from '@/api/gen/create'
import msgUtil from '@/utils/msgUtil'
import { listGenAhthorCombo } from '@/api/common/common'
import PageUtil from '@/utils/PageUtil'
import ComboConst from '@/utils/ComboConst'

// 定义table 的表单
const tableForm = {
  id: null,
  authorId: null,
  tablename: null,
  javaPackage: '',
  isPage: 1,
  isAdd: 1,
  isUpdate: 1,
  isDelete: 1,
  isView: 0,
  firstCode: '',
  firstName: '',
  secondCode: '',
  secondName: '',
  pkCreate: 1,
  pkField: '',
  orderField: ''
}

export default {
  data() {
    return {
      isEdit: false,
      tableForm: tableForm,
      dialogTableFormVisible: false, // 弹出的新增修改表单窗口
      dialogGenCodeVisible: false, // 弹出的生成代码窗口
      dialogGenSqlCodeVisible: false, // 弹出的生成代码窗口
      pkCreateOptions: ComboConst.pkCreateOptions, // 主键生成方式
      yesNoOptions: ComboConst.yesNoOptions, // 是否选择
      genCodeText: '', // 弹窗java代码
      genSqlCodeText: '', // 弹窗Sql的代码
      selTableId: 0, // 选中行的tableId
      selType: 0, // 选中的创建文件类型
      tableKey: 0,
      list: null,
      listGenAhthorCombo: [],
      listLoading: false,
      listQuery: JSON.parse(localStorage.getItem('GenTableQuery')) || {
        authorId: 0
      },
      rules: {
        tablename: [{ required: true, trigger: 'blur', message: '数据表名不能为空' }],
        description: [{ required: true, trigger: 'blur', message: '数据描述不能为空' }],
        javaPackage: [{ required: true, trigger: 'blur', message: 'java包名不能为空' }],
        apiUrl: [{ required: true, trigger: 'blur', message: 'apiUrl全局配置不能为空' }],
        firstCode: [{ required: true, trigger: 'blur', message: '一级模块代码不能为空' }],
        secondCode: [{ required: true, trigger: 'blur', message: '二级模块代码不能为空' }],
        firstName: [{ required: true, trigger: 'blur', message: '一级模块名称不能为空' }],
        secondName: [{ required: true, trigger: 'blur', message: '二级模块名称不能为空' }],
        pkField: [{ required: true, trigger: 'blur', message: '主键字段不能为空' }],
        displayOrder: [{ required: true, trigger: 'blur', message: '排序字段不能为空' }]
      }
    }
  },
  created() {
    if (this.listQuery.authorId !== '') {
      this.listGenTable()
    }
    this.listGenAhthor()// 用户列表
  },
  methods: {
    isPageFormatter(row) {
      return PageUtil.formatValue(ComboConst.yesNoOptions, row.isPage)
    },
    isAddFormatter(row) {
      return PageUtil.formatValue(ComboConst.yesNoOptions, row.isAdd)
    },
    isUpdateFormatter(row) {
      return PageUtil.formatValue(ComboConst.yesNoOptions, row.isUpdate)
    },
    isDeleteFormatter(row) {
      return PageUtil.formatValue(ComboConst.yesNoOptions, row.isDelete)
    },
    isViewFormatter(row) {
      return PageUtil.formatValue(ComboConst.yesNoOptions, row.isView)
    },
    // 获取所有用户
    async listGenAhthor() {
      await listGenAhthorCombo({}).then(response => {
        this.listGenAhthorCombo = response.data
      })
    },
    listGenTable() {
      if (this.listQuery.authorId === '') {
        msgUtil.error2('请选择用户')
        return
      }

      this.listLoading = true
      listGenTable(this.listQuery).then(response => {
        this.list = response.data
        setTimeout(() => {
          this.listLoading = false
        }, 100)
      })
      this.selTableId = 0
      localStorage.setItem('GenTableQuery', JSON.stringify(this.listQuery))
    },
    // 按钮查询
    handleFilter() {
      this.listGenTable()
    },
    // 删除
    handleDelete(row) {
      msgUtil.confirm('确认删除配置?').then(async() => {
        await deleteGenTable({ id: row.id })
        msgUtil.success2('删除成功!')
        this.listGenTable()
      })
    },
    // 处理表格单选
    handleCurrentChange(val) {
      if (val !== null) {
        this.$refs.genTable.toggleRowSelection(val)
      }
    },
    handleSelectionChange(val) {
      if (val.length > 1) {
        this.$refs.genTable.clearSelection()
        this.$refs.genTable.toggleRowSelection(val[val.length - 1])
      } else if (val.length === 0) {
        this.selTableId = 0
      } else {
        this.multipleSelection = val[val.length - 1]
        this.selTableId = val[0].id
      }
    },
    // 查看字段明细
    handleViewField(row) {
      this.$router.push({
        path: '/gen/field/index',
        query: { tableId: row.id, authorId: this.listQuery.authorId }
      })
    },
    // 打开tableform窗口
    openDialogTableForm(isEdit, row) {
      this.isEdit = isEdit
      if (isEdit) {
        this.tableForm = row
        this.dialogTableFormVisible = true
      } else {
        this.dialogTableFormVisible = true
        this.$refs.tableForm.resetFields()
      }
    },
    // 保存数据表配置
    saveTable() {
      if (this.listQuery.authorId === '') {
        msgUtil.error2('请选择用户')
        return
      }

      this.$refs.tableForm.validate(valid => {
        if (valid) {
          if (this.isEdit) {
            this.tableForm.authorId = this.authorId
            updateGenTable(this.tableForm).then(response => {
              msgUtil.success()
              this.dialogTableFormVisible = false
              this.listGenTable()
            })
          } else {
            this.tableForm.authorId = this.listQuery.authorId
            addGenTable(this.tableForm).then(response => {
              msgUtil.success()
              this.dialogTableFormVisible = false
              this.listGenTable()
            })
          }
        }
      })
    },
    // 生成代码，请求生成，弹出框显示代码
    createCode(type) {
      this.selType = type
      this.genCodeText = ''
      // 判断是否选中行
      if (this.selTableId === 0) {
        msgUtil.error2('请选择数据表')
        return
      }
      getGenCode(
        { authorId: this.listQuery.authorId, tableId: this.selTableId, type: type }
      ).then(response => {
        this.genCodeText = response.data
        this.dialogGenCodeVisible = true
      }).catch((response) => {
        msgUtil.error2(response.data)
      })
    },
    // 全部生成
    createAllCode(type) {
      this.selType = type
      this.genCodeText = ''
      // 判断是否选中行
      if (this.selTableId === 0) {
        msgUtil.error2('请选择数据表')
        return
      }
      this.checkFileExist()
    },
    // 拷贝代码
    copyCode() {
      this.$copyText(this.genCodeText).then(function(e) {
        msgUtil.success2('复制成功')
      }, function(e) {
        alert('Can not copy')
      })
    },
    // 判断文件是否存在
    checkFileExist() {
      const param = { authorId: this.listQuery.authorId, tableId: this.selTableId, type: this.selType }
      checkFileExist(param).then(response => {
        const checkStr = response.data
        if (checkStr !== '') {
          msgUtil.confirm(checkStr + '</br>是否覆盖？').then(async() => {
            await this.createFile(param)
          })
        } else {
          this.createFile(param)
        }
      }).catch((response) => {
        msgUtil.error2(response.data)
      })
    },
    // 生成文件
    createFile(param) {
      createFile(param).then(response => {
        msgUtil.success2('生成成功')
        this.dialogGenCodeVisible = false
      }).catch((response) => {
        msgUtil.error2(response.data)
      })
    },
    // 生成建表脚本
    createSqlCode() {
      this.genSqlCodeText = ''
      // 判断是否选中行
      if (this.selTableId === 0) {
        msgUtil.error2('请选择数据表')
        return
      }
      getGenSqlCode({ authorId: this.listQuery.authorId, tableId: this.selTableId }).then(response => {
        this.genSqlCodeText = response.data
        this.dialogGenSqlCodeVisible = true
      }).catch((response) => {
        msgUtil.error2(response.data)
      })
    },
    //   拷贝Sql代码
    copySqlCode() {
      this.$copyText(this.genSqlCodeText).then(function(e) {
        msgUtil.success2('复制成功')
      }, function(e) {
        alert('Can not copy')
      })
    },
    // 加载数据表字段
    loadDbField() {
      this.$router.push({
        path: '/gen/field/loadField',
        query: { authorId: this.listQuery.authorId, tableId: this.selTableId }
      })
    }
  }
}
</script>

